package com.sengled.cloud.biz.union.mgt.api.config;

import com.sengled.cloud.biz.union.mgt.common.util.FastJsonUtils;
import com.sengled.cloud.biz.union.mgt.model.dto.UnionUser;
import com.sengled.cloud.domain.CustomerSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private SessionRegistry sessionRegistry;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws ServletException, IOException {
        UnionUser unionUser = (UnionUser) authentication.getPrincipal();
        HttpSession session = request.getSession();
        CustomerSession customerSession = new CustomerSession();

//        CustomerSession customerSession = new CustomerSession();
        customerSession.setCustomerId(unionUser.getId());
        customerSession.setUser(unionUser.getUsername());
        customerSession.setPwd(unionUser.getPassword());
        System.out.println(FastJsonUtils.toJSONString(customerSession) + " = " + session.getId());
        session.setAttribute("user", customerSession);
//        String key = "sengled_union_";
//        RedisUtil.setStrValueByKey(key + customerSession.getCustomerId(), session.getId());
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json");
//        String sessionId = request.getSession().getId();
//        response.getWriter().println("{\"ok\":\"1\",\"msg\":\"登录成功\",\"date\":\"" + sessionId + "\"}");


        request.getRequestDispatcher("/api/v1/login/data").forward(request,response);
    }
}
